package com.yfqy.app.modules.order.director;

import com.yfqy.app.domain.entity.ProductSpu;
import com.yfqy.app.domain.entity.PromotionProduct;
import com.yfqy.app.enums.OrderType;
import com.yfqy.app.modules.order.dto.OrderAmountDTO;
import com.yfqy.app.modules.order.dto.OrderCreateRequest;
import com.yfqy.app.modules.order.dto.OrderItemRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 特价活动订单
 */
@Service
@Slf4j
public class SpecialOrderCreateBuilderDirector extends AbstractOrderCreateBuilderDirector {


    @Override
    public OrderType getOrderType() {
        return OrderType.SPECIAL;
    }

    @Override
    public void validateProducts(OrderCreateRequest request) {
        // nothing to do
    }

    @Override
    public void specificValidate(OrderCreateRequest request) {

        // 1. 批量获取商品信息并验证
        OrderItemRequest item = request.getItems().get(0);
        Map<Long, ProductSpu> spuMap = validateProductInfo(item);

        // 2. 验证促销活动
        PromotionProduct promotionProduct = getAndValidatePromotion(request.getPromotionId(), item.getSkuId());
        item.setPromotionProductId(promotionProduct.getId());

        // 3. 价格校验
        validatePrice(item, spuMap, promotionProduct);

        // 4. 库存校验
        validateStock(item, spuMap, promotionProduct);

        // 5. 限购校验
        validatePurchaseLimit(item, request.getUserId(), promotionProduct);

        log.info("订单特殊校验完成，订单类型：{}", getOrderType());
    }

    @Override
    public void validRequiredParam(OrderCreateRequest request) {
        validateParams(request);
        specificValidate(request);
    }

    @Override
    public OrderAmountDTO calculateAmount(OrderCreateRequest request) {
        // 1. 重新计算商品总金额
        OrderItemRequest item = request.getItems().get(0);
        BigDecimal calculatedTotal = calculateItemTotalAmount(item);

        OrderAmountDTO amountDTO = request.getOrderAmountDTO();
        // 2. 校验并修正总金额
        if (amountDTO.getTotalAmount() == null || amountDTO.getTotalAmount().compareTo(calculatedTotal) != 0) {
            log.warn("前端总金额计算错误，已修正。前端值: {}, 计算值: {}", amountDTO.getTotalAmount(), calculatedTotal);
            amountDTO.setTotalAmount(calculatedTotal);
        }

        // 3. 重新计算实付金额（总金额 - 优惠 - 积分抵扣）
        BigDecimal paymentAmount = calculatedTotal;

        // 4. 特价活动优惠的价格
        amountDTO.setDiscountAmount(item.getSkuOriginalPrice().subtract(item.getUnitPrice()));

        // 5. 如果有积分抵扣
        if (request.isUsePoints()) {
            applyPointsDeduction(amountDTO, paymentAmount);
        } else {
            resetPointsDeduction(amountDTO);
        }

        // 6. 设置最终实付金额
        paymentAmount = paymentAmount.subtract(amountDTO.getPointAmount());
        amountDTO.setPaymentAmount(paymentAmount);

        // 7. 最终商品实付金额是否免运费
        calculateFreightAmount(amountDTO);

        // 8. 更新前端的amount对象
        request.setOrderAmountDTO(amountDTO);
        return amountDTO;
    }

}
